package com.hitqz.robot.biz.config;

import com.hitqz.robot.common.core.util.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.List;
import java.util.Objects;

@ControllerAdvice
@Slf4j
public class ValidatedExceptionHandler {
    /**
     * 处理@Validated参数校验失败异常
     * @param exception 异常类
     * @return 响应
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler(HttpServletRequest request,MethodArgumentNotValidException exception){
        // 获取请求 URL 和方法
        String requestUrl = request.getRequestURI();
        String httpMethod = request.getMethod();
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                log.warn("Bad Request[{} {}] Parameters: dto entity [{}],field [{}],message [{}]",httpMethod, requestUrl, fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                stringBuilder.append(fieldError.getDefaultMessage());
            });
        }
        return R.failed(stringBuilder.toString());
    }


    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R typeExceptionHandler(HttpServletRequest request,MethodArgumentTypeMismatchException exception){
        // 获取请求 URL 和方法
        String requestUrl = request.getRequestURI();
        String httpMethod = request.getMethod();
        // 获取参数名称
        String parameterName = exception.getName();
        Object value = exception.getValue();
        // 避免重复打印错误
        if (value instanceof String && Objects.equals(value,"undefined")){
            return R.ok();
        }
        // 获取期望的参数类型
        String expectedType = exception.getRequiredType() != null ? exception.getRequiredType().getSimpleName() : "unknown";
        // 获取错误信息
        String errorMessage = String.format("参数类型不匹配: 参数 '%s' 应为 '%s' 类型。", parameterName, expectedType);
        // 记录错误日志，包括请求的接口和方法信息
        log.error("接口 [{} {}] 出现参数类型不匹配异常: {}", httpMethod, requestUrl, errorMessage);
        return R.failed(errorMessage);
    }

}
